package com.iwomy.envpro.platform.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.iwomy.envpro.admin.api.dto.UserInfo;
import com.iwomy.envpro.admin.api.entity.SysUser;
import com.iwomy.envpro.admin.api.feign.RemoteUserService;
import com.iwomy.envpro.app.api.dto.AppUserInfo;
import com.iwomy.envpro.app.api.entity.AppUser;
import com.iwomy.envpro.app.api.feign.RemoteAppUserService;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.data.tenant.TenantBroker;
import com.iwomy.envpro.common.security.annotation.Inner;
import com.iwomy.envpro.common.security.util.SecurityUtils;
import com.iwomy.envpro.common.xss.core.XssCleanIgnore;
import com.iwomy.envpro.platform.service.MpService;
import com.iwomy.envpro.platform.utils.RedisClient;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 微信公众号接口
 *
 * @author pig
 * @date 2023-08-29 17:58:11
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/mp")
@Tag(description = "mp", name = "微信公众号接口")
@Slf4j
public class MpController {

	private final WxMpService wxMpService;

//	private final RemoteAppUserService remoteAppUserService;

	private final RemoteUserService remoteUserService;

	private final MpService mpService;


	/**
	 * 获取公众号授权地址
	 *
	 * @return
	 */
	@GetMapping("oauthUrl")
	@Inner(value = false)
	public R oauthUrl(HttpServletRequest request) {
		String host = request.getHeader("Host");
		log.info("Host:{}", host);
		String url = wxMpService.getOAuth2Service().buildAuthorizationUrl("https://mp.iwomy.com/#/pages/center/index", WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
		return R.ok(url);
	}

	/**
	 * 移动端和微信公众号端绑定
	 *
	 * @return
	 */
	@GetMapping("redirect")
	public R redirect(@RequestParam("code") String code) throws WxErrorException {
		WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
		WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
		log.info("WxOAuth2UserInfo:{}", JSONObject.toJSONString(wxMpUser));
		String openid = wxMpUser.getOpenid();

		if (ObjectUtil.isEmpty(openid)) {
			return R.failed(wxMpUser);
		}
		log.info(JSONObject.toJSONString(SecurityUtils.getUser()));
		R<UserInfo> info = remoteUserService.info(SecurityUtils.getUser().getUsername(), SecurityConstants.FROM_IN);
		SysUser userInfo = Optional.ofNullable(info.getData().getSysUser()).get();
		if (ObjectUtil.isNull(userInfo)) return R.failed("授权失败");
		userInfo.setWxOpenid(openid);
		userInfo.setWxNickname(wxMpUser.getNickname());
		userInfo.setWxAvatar(wxMpUser.getHeadImgUrl());
		log.info(JSONObject.toJSONString(userInfo));
		R<Boolean> booleanR = remoteUserService.authorizationBinding(userInfo, SecurityConstants.FROM_IN);
//		log.info(JSONObject.toJSONString(wxMpUser));
//		log.info(JSONObject.toJSONString(booleanR));
		return R.ok();
	}

	/**
	 * 移动端和微信公众号端绑定
	 *
	 * @return
	 */
	@GetMapping("unbind")
	public R unbind() throws WxErrorException {

		R<UserInfo> info = remoteUserService.info(SecurityUtils.getUser().getUsername(), SecurityConstants.FROM_IN);
		SysUser userInfo = Optional.ofNullable(info.getData().getSysUser()).get();
		userInfo.setWxOpenid(null);
		userInfo.setWxAvatar(null);
		userInfo.setWxNickname(null);
		log.info(JSONObject.toJSONString(userInfo));
		R<Boolean> booleanR = remoteUserService.authorizationBinding(userInfo, SecurityConstants.FROM_IN);
		log.info(JSONObject.toJSONString(booleanR));
		return R.ok();
	}


	/**
	 * 微信接入校验处理
	 *
	 * @param signature 微信签名
	 * @param timestamp 时间戳
	 * @param nonce     随机数
	 * @param echostr   随机字符串
	 * @return
	 */
	@XssCleanIgnore
	@GetMapping(produces = "text/plain;charset=utf-8")
	@Inner(value = false)
	public String authGet(
			@RequestParam(name = "signature", required = false) String signature,
			@RequestParam(name = "timestamp", required = false) String timestamp,
			@RequestParam(name = "nonce", required = false) String nonce,
			@RequestParam(name = "echostr", required = false) String echostr) {

		log.info("接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

		if (StrUtil.isAllBlank(signature, timestamp, nonce, echostr)) {
			throw new IllegalArgumentException("请求参数非法，请核实!");
		}
		return echostr;
	}


	/**
	 * 微信消息处理
	 *
	 * @param requestBody  请求报文体
	 * @param signature    微信签名
	 * @param encType      加签方式
	 * @param msgSignature 微信签名
	 * @param timestamp    时间戳
	 * @param nonce        随机数
	 * @return
	 */
	@XssCleanIgnore
	@PostMapping(produces = "application/xml; charset=UTF-8")
	public String post(@RequestBody String requestBody,
					   @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
					   @RequestParam("nonce") String nonce, @RequestParam("openid") String openid,
					   @RequestParam(name = "encrypt_type", required = false) String encType,
					   @RequestParam(name = "msg_signature", required = false) String msgSignature) {
		log.info(
				"接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
						+ " timestamp=[{}], nonce=[{}], requestBody=[{}] ",
				openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
		return "欢迎您关注智慧环保云助手，请点击我的设备进行登录，方便实时接收报警信息";


	}


}